import useDictStore from '@/store/modules/dict';
import { getDicts } from '@/api/system/dict/data';
import { type ToRefs, ref, toRefs } from 'vue';

type DictItem = {
  label: string;
  value: string;
  elTagType: string;
  elTagClass: string;
};

// 所有字典类型 key 推断提示
type DictEnumType = {
  sys_user_sex: '用户性别';
  sys_show_hide: '菜单状态';
  sys_normal_disable: '系统开关';
  sys_job_status: '任务状态';
  sys_job_group: '任务分组';
  sys_yes_no: '系统是否';
  sys_notice_type: '通知类型';
  sys_notice_status: '通知状态';
  sys_oper_type: '操作类型';
  sys_common_status: '系统状态';
  jy_pay_type: '支付方式';
  sys_news_type: '官网文章类型';
  jy_pay_status: '支付状态';
  certificate: '证书';
  order_status: '订单状态';
  jy_invoice_status: '开票状态';
  sys_news_status: '官网文章状态';
  overdue: '是否过期';
  rate_of_learning: '学习进度';
  stuby_hour_status: '学习申报结果';
};

type DictSend = {
  [K in keyof DictEnumType]: DictItem[];
};
/**
 * 获取字典数据
 */
export function useDict<K extends keyof DictEnumType>(
  ...args: (keyof DictEnumType)[]
): ToRefs<Pick<DictSend, K>> {
  const res = ref<DictSend | Record<string, any>>({});
  return ((): ToRefs<Pick<DictSend, K>> => {
    args.forEach((dictType) => {
      res.value[dictType] = [];
      // @ts-ignore
      const dicts = useDictStore().getDict(dictType) as DictItem[];
      if (dicts) {
        res.value[dictType] = dicts;
      } else {
        getDicts(dictType).then((resp) => {
          res.value[dictType] = resp.data.map((p) => ({
            label: p.dictLabel,
            value: p.dictValue,
            elTagType: p.listClass,
            elTagClass: p.cssClass,
          }));
          useDictStore().setDict(dictType, res.value[dictType]);
        });
      }
    });

    return toRefs<Pick<DictSend, K>>(res.value as DictSend);
  })();
}
